package com.akxy.pt.tsdb.influxdb.operator;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Mengfly
 */
public class FilterOperator implements Operator{

    private static final int AND = 0;
    private static final int OR = 1;

    private final List<Integer> operations = new ArrayList<>();
    private final List<String> conditions = new ArrayList<>();

    public FilterOperator(String field, String val) {
        addCondition(field, val, AND);
    }

    public FilterOperator and(String field, String val) {
        return addCondition(field, val, AND);
    }

    public FilterOperator or(String field, String val) {
        return addCondition(field, val, OR);
    }

    private FilterOperator addCondition(String field, String val, int op) {
        String condition =  String.format("r.%s == \"%s\"", field, val);
        operations.add(op);
        conditions.add(condition);
        return this;
    }

    @Override
    public String operatorString() {
        StringBuilder conditionBuilder = new StringBuilder();
        conditionBuilder.append("(r) => ");
        for (int i = 0; i < conditions.size(); i++) {
            if (i != 0) {
                Integer op = operations.get(i);
                if (op == AND) {
                    conditionBuilder.append(" and ");
                } else if (op == OR) {
                    conditionBuilder.append(" or ");
                }
            }
            conditionBuilder.append(conditions.get(i));
        }
        return String.format("|> filter(fn:%s)", conditionBuilder.toString());
    }
}
